package com.dbapp.shopping.controller;

import com.dbapp.shopping.domain.Good;
import com.dbapp.shopping.domain.User;
import com.dbapp.shopping.domain.Record;
import com.dbapp.shopping.service.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

@Controller
@RequestMapping("/profile={username}")
public class ProfileController {

    private Service service;

    @Autowired
    public ProfileController(Service service)
    {
        this.service = service;
    }

    @GetMapping
    public String profile(Model model, Principal principal, @PathVariable("username") String username){
        User current = service.getUserByUsername(username);
        Authentication authentication = (Authentication) principal;
        User user = (User) authentication.getPrincipal();
        if (principal != null && authentication.isAuthenticated()) {
            model.addAttribute("status", true)
                    .addAttribute("user", (User) authentication.getPrincipal())
                    .addAttribute("current", current);
        } else {
            model.addAttribute("status", false);
            return "redirect:/";
        }

        List<Good> displaygoods = service.findGoodsByUser(current);
        List<Record> orders = service.findRecordsByUser(current);
        model.addAttribute("displaygoods", displaygoods);
        model.addAttribute("orders", orders);

        return "profile";
    }
}
